<?php
/**
 ***** 扶摇而上、抱守本真 ******
 * @author Dana
 * @Date 2021/6/25
 */

$secret_word = 'if i ate spinach';

function validate($user,$pass){
    $users = [
        'david'=>'123456',
        'adam'=>'123456'
    ];

    if(isset($users[$user]) && $users[$user] === $pass){
        return true;
    }else{
        return false;
    }
}

if(validate($_POST['username'],$_POST['password'])){
    setcookie('login',$_POST['username'].','.md5($_POST['username'].$secret_word),30);
}
    echo "<form method='post' action={$_SERVER['php_self']} > <br>";
    echo "username :<input type = 'text' name='username'> <br>";
    echo "password :<input type = 'password' name='password'> <br>";
    echo "<input type = 'submit' value='Log In'> \n";


unset($username);
if(isset($_COOKIE['login'])){
   list($c_username,$cookie_hash) = explode(',', $_COOKIE['login']);
   if(md5($c_username.$secret_word) == $cookie_hash){
       $username = $c_username;
   }else{
       print "you have send a bad cookie";
   }
}

if(isset($username)){
    print  "welcome ,$username";
}else{
    print "welcome,anonymous user";
}




